package com.jxb.currentLimiting;

import java.util.LinkedList;
import java.util.Random;

/**
 * 滑动窗口限流算法
 *
 * @author jiaobo
 * @date Created in 2024/10/15 21:58
 **/
public class SlidingTimeWindow {

    //服务访问次数
    Long counter = 0L;
    //记录滑动窗口格子
    LinkedList<Long> slots = new LinkedList<>();

    public static void main(String[] args) throws InterruptedException {
        SlidingTimeWindow slidingTimeWindow = new SlidingTimeWindow();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    slidingTimeWindow.doCheck();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //模拟请求，count数加一
        while (true) {
            slidingTimeWindow.counter++;
            Thread.sleep(new Random().nextInt(15));
        }
    }

    //创建各自，每个格子100ms
    private void doCheck() throws InterruptedException {
        while (true) {
            slots.addLast(counter);
            if (slots.size() > 10) {
                slots.remove();
            }
            //比较最后一个和第一个，两者相差100以上就限流
            if ((slots.peekLast() - slots.peekFirst()) > 100) {
                System.out.println("限流了...");
                //TODO 修改限流标记为true
            }else {
                //TODO 修改限流标记为false
            }
            Thread.sleep(100);
        }
    }

}
